﻿/**************************************************************
 *
 * 唯一标识：33e846df-ca3b-4dff-9c62-6fb8a0593b89
 * 命名空间：Sgr.Caching
 * 创建时间：2023/8/23 7:26:44
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using System;
using System.Collections.Generic;
using System.Text;

namespace Sgr.Caching
{
    public class CacheOptions
    {
        /// <summary>
        /// 绝对过期时间（秒数）的缺省值
        /// </summary>
        public int? DefaultAbsoluteExpirationSecond { get; set; } = 3600;

        /// <summary>
        /// 滑动过期时间（秒数）的缺省值
        /// </summary>
        public int? DefaultSlidingExpirationSecond { get; set; } = 600;

        /// <summary>
        /// 内存缓存锁的数量
        /// </summary>
        public int? StripedLockCount { get; set; } = 1024;

        /// <summary>
        /// 缓存锁的超时时间（毫秒）
        /// </summary>
        public int LockTimeoutMilliseconds { get; set; } = 10000;

        /// <summary>
        /// 防止缓存击穿的空值缓存时间（秒）
        /// </summary>
        public int NullValueExpirationSeconds { get; set; } = 30;

        /// <summary>
        /// 创建缓存项选项
        /// </summary>
        /// <returns></returns>
        public CacheEntryOptions CreateCacheEntryOptions()
        {
            var cacheEntryOptions = new CacheEntryOptions();
            if (this.DefaultAbsoluteExpirationSecond.HasValue)
                cacheEntryOptions.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(this.DefaultAbsoluteExpirationSecond.Value);

            if (this.DefaultSlidingExpirationSecond.HasValue)
                cacheEntryOptions.SlidingExpiration = TimeSpan.FromSeconds(this.DefaultSlidingExpirationSecond.Value);

            return cacheEntryOptions;
        }

        private CacheEntryOptions? _nullPreset;

        /// <summary>
        /// 创建空值缓存项选项
        /// </summary>
        /// <returns></returns>
        public CacheEntryOptions CreateNullValueCacheEntryOptions()
               => _nullPreset ??= new CacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(NullValueExpirationSeconds) };
    }
}